package cn.evilelf.util;

import java.util.HashMap;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.evilelf.util.exceptions.InvalidOptionException;

public class Options {

	private static String optionNameReg = "\\-{1,2}(\\w+)";
	// private static String optionValueReg = "^\\-(.+)";

	private HashMap<String, String> options;

	@SuppressWarnings("unused")
	private Options() {

	}

	public Options(String args[]) throws InvalidOptionException {
		options = new HashMap<String, String>();
		Pattern p = Pattern.compile(optionNameReg);

		int i = 0;
		while (i < args.length) {
			// String curOption = args[i];
			Matcher m = p.matcher(args[i]);
			if (m.find()) {
				// System.out.println(m.group(1));
				if ((i + 1) < args.length && !args[i + 1].startsWith("-")) {
					options.put(m.group(1), args[i + 1]);
					i += 2;
				} else {
					options.put(m.group(1), null);
					i += 1;
				}
			} else {
				throw new InvalidOptionException();
			}
		}
	}

	public String putOptions(String optionName, String optionValue) {
		return options.put(optionName, optionValue);
	}

	public String getOptionValue(String optionName) {
		return options.get(optionName);
	}

	public String[] getOptionsNameArray() {
		Set<String> optionsSet = options.keySet();
		return (String[]) optionsSet.toArray();
	}

	public boolean containsOption(String option) {
		return options.containsKey(option);
	}

	public static void main(String[] args) {
		String[] testArgs = { "-c", "code", "-e", "edit", "-f", "-t", "-n",
				"45", "-p", "--version", "2.1.3" };
		try {
			Options options = new Options(testArgs);
			System.out.println(options.getOptionValue("version"));
		} catch (InvalidOptionException ie) {

		}
	}
}
